﻿using System;
using System.Globalization;
using System.Windows;
using System.Windows.Data;
using System.Windows.Media;
using System.Windows.Media.Imaging;

namespace Alfa.Common.ValueConverters {
	/// <summary>
	/// Value converter that translates string uri to <see cref="ImageSource"/>.
	/// </summary>
	public sealed class StringToImageSourceConverter : IValueConverter {
		/// <summary>
		/// Converts string value to <see cref="ImageSource"/>.
		/// </summary>
		/// <param name="value">Value to convert. Should be string.</param>
		/// <param name="targetType"></param>
		/// <param name="parameter"></param>
		/// <param name="culture"></param>
		/// <returns>Converted value (ImageSource)</returns>
		public object Convert(object value, Type targetType, object parameter, CultureInfo culture) {
			if (value is string && value != null && (string)value != "") {
				try {
					Uri uri = new Uri((string)value, UriKind.RelativeOrAbsolute);
					return new BitmapImage(uri);
				} catch {
					return null;
				}
			}
			return null;
		}

		/// <summary>
		/// Converts back <see cref="ImageSource"/> value to string.
		/// </summary>
		/// <param name="value">Value to convert. Should be <see cref="ImageSource"/>.</param>
		/// <param name="targetType"></param>
		/// <param name="parameter"></param>
		/// <param name="culture"></param>
		/// <returns>Converted value (string)</returns>
		public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) {
			return value is ImageSource ? ((ImageSource)value).ToString( ) : "";
		}
	}
}
